package 极客算法训练营.chapter07;

import java.util.*;

public class 全排列2 {
    class Solution {
        private List<List<Integer>> ans;
        private Deque<Integer> path;
        private boolean[] flag;//是否在本轮下探中访问过
        private int length;

        public List<List<Integer>> permuteUnique(int[] nums) {
            ans = new ArrayList<>();
            path = new LinkedList<>();
            length = nums.length;
            flag = new boolean[length];
            Arrays.sort(nums);
            dfs(0, nums, path);
            return ans;
        }

        public void dfs(int depth, int[] nums, Deque<Integer> path) {
            if (depth == length) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < length; i++) {
                //剪枝：flag[i]==false表示在层级剪枝；flag[i]==true表示在叶子上剪枝
                if (i > 0 && nums[i] == nums[i - 1] && !flag[i- 1]) {
                    continue;
                }
                if (flag[i]) {
                    continue;
                }
                flag[i] = true;
                path.addLast(nums[i]);
                dfs(depth + 1, nums, path);
                flag[i] = false;
                path.removeLast();
            }
        }
    }
}
